package com.mibus.mibusmobile;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.location.Location;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Looper;
import android.os.PowerManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.*;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;


import android.content.Context;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.Toast;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



public class RecorridoActivity extends Activity implements OnClickListener,OnItemSelectedListener{

    private Button btnHacerRequest, btnCerrarSesion, btnActualizarSpinner;
    private TextView tvPos, tvInfo;
    private Spinner spRutas, spHorarios;

    private JSONArray cJSON;
    private Integer id_horario;
    private Integer id_ruta;
    private Integer id_recorrido;
    private double latitud=0;
    private double longitud=0;
    private double velocidad=0;
    private LocationManager mlocManager ;
    private LocationListener mlocListener ;
    boolean primeraVez;
    private String hash_session = "";
    private String update_time = "";
    private String id_conductor = "";
    private String id_bus = "";

    private PowerManager.WakeLock mWakeLock;
    private final String MOBILE_APP_URL = "http://mibus.eia.edu.co/Tablet/";
    private MySQLiteHelperRecorrido mDbHelper;
    private SimpleDateFormat dateFormater;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        this.mWakeLock.acquire();

        btnHacerRequest = (Button)findViewById(R.id.btnHacerRequest);
        tvPos = (TextView)findViewById(R.id.tvPos);
        tvInfo = (TextView)findViewById(R.id.tvInfo);
        spRutas = (Spinner)findViewById(R.id.spRutas);
        spHorarios = (Spinner)findViewById(R.id.spHorarios);
        btnCerrarSesion = (Button) findViewById(R.id.btnCerrarSesion1);
        btnActualizarSpinner = (Button) findViewById(R.id.btnActualiarSpinner);
        mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        mlocListener = new MyLocationListenerIni();


        btnHacerRequest.setOnClickListener(this);
        btnCerrarSesion.setOnClickListener(this);
        btnActualizarSpinner.setOnClickListener(this);


        primeraVez=true;
        Bundle bundleReceptor = getIntent().getExtras();
        hash_session = bundleReceptor.getString("hash_session");
        update_time = bundleReceptor.getString("update_time");
        id_bus = bundleReceptor.getString("id_bus");
        id_conductor = bundleReceptor.getString("id_conductor");

        mDbHelper = new MySQLiteHelperRecorrido(this);
        dateFormater = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

    }

    protected void onResume() {
        super.onResume();
        tvInfo.setText("Esperando Posicion");
        autoLoginRecorridoRealizado();
        //mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mlocListener, Looper.myLooper()); // una sola peticion de localizacion
        hacerRequest();

        btnActualizarSpinner.setEnabled(false);
        btnHacerRequest.setEnabled(false);
    }
    protected void onDestroy() {
        this.mWakeLock.release();
        super.onDestroy();
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
        Spinner spinner = (Spinner)adapterView;
        String selectedItem= adapterView.getItemAtPosition(pos).toString();

        if(spinner.getId() == R.id.spRutas){
            if(pos != 0){
                try{
                    List<String> contenidoSpinner =  new ArrayList<String>();
                    contenidoSpinner.add("Seleccionar Horario");

                    for(int i = 0; i < cJSON.length(); i++){
                        JSONObject JSONrecorrido = cJSON.getJSONObject(i);
                        JSONObject  JSONruta= JSONrecorrido.getJSONObject("Ruta");
                        JSONObject JSONhorario = JSONrecorrido.getJSONObject("Horario");

                        if(JSONruta.getString("nombre_ruta").equals(selectedItem)){
                            contenidoSpinner.add(JSONhorario.getString("hora_salida"));
                            id_ruta=JSONruta.getInt("id_ruta");
                        }
                    }

                    ArrayAdapter<String> adapter =  new ArrayAdapter<String>(this,R.layout.spinner_item, contenidoSpinner);
                    spHorarios.setAdapter(adapter);
                    spHorarios.setOnItemSelectedListener(this);
                }catch (Exception e){
                }
            }else{
                List<String> contenidoSpinner =  new ArrayList<String>();
                contenidoSpinner.add("");
                id_ruta = null;
                id_horario = null;
                ArrayAdapter<String> adapter =  new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, contenidoSpinner);
                spHorarios.setAdapter(adapter);
            }
        }

        if(spinner.getId() == R.id.spHorarios){
            if(pos != 0){
                try{
                    if(latitud != 0 && longitud != 0){
                        btnHacerRequest.setEnabled(true);
                    }
                    for(int i = 0; i < cJSON.length(); i++){
                        JSONObject jsonRecorrido = cJSON.getJSONObject(i);
                        JSONObject  jsonRuta= jsonRecorrido.getJSONObject("Ruta");
                        JSONObject jsonHorario = jsonRecorrido.getJSONObject("Horario");
                        String ruta=spRutas.getSelectedItem().toString();
                        if(jsonRuta.getString("nombre_ruta").equals(ruta) && jsonHorario.getString("hora_salida").equals(selectedItem)){
                            id_horario = jsonHorario.getInt("id_horario");
                        }
                    }
                }catch (Exception e){
                    //btnHacerRequest.setEnabled(false);
                }
            }else{
                id_horario=null;
                btnHacerRequest.setEnabled(false);
            }
        }
    }


    public void onNothingSelected(AdapterView<?> adapterView) {}

    public void onClick(View view) {
        if(view.getId() == R.id.btnHacerRequest){
            try{
                for(int i = 0; i < cJSON.length(); i++){
                    JSONObject jsonRecorridoObjeto = cJSON.getJSONObject(i);
                    JSONObject  jsonRecorrido= jsonRecorridoObjeto.getJSONObject("Recorrido");

                    if(id_horario == jsonRecorrido.getInt("id_horario") && id_ruta == jsonRecorrido.getInt("id_ruta")){
                       id_recorrido= jsonRecorrido.getInt("id_recorrido");
                    }
                }
                String fechaActualStr = dateFormater.format(new Date());

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(9);
                nameValuePairs.add(new BasicNameValuePair("tag", "INICIAR"));
                nameValuePairs.add(new BasicNameValuePair("hash_session", hash_session));
                nameValuePairs.add(new BasicNameValuePair("id_recorrido",id_recorrido.toString()));
                nameValuePairs.add(new BasicNameValuePair("id_conductor", id_conductor));
                nameValuePairs.add(new BasicNameValuePair("id_bus", id_bus));
                nameValuePairs.add(new BasicNameValuePair("latitud", String.valueOf(latitud)));
                nameValuePairs.add(new BasicNameValuePair("longitud", String.valueOf(longitud)));
                nameValuePairs.add(new BasicNameValuePair("velocidad", String.valueOf(velocidad)));
                nameValuePairs.add(new BasicNameValuePair("puestos_ocupados", "0"));
                nameValuePairs.add(new BasicNameValuePair("fecha_solicitar_posicion",fechaActualStr));
                nameValuePairs.add(new BasicNameValuePair("fecha_posicion_obtenida",fechaActualStr));

                RequestPost requestPost =  new RequestPost(nameValuePairs, this);
                String resultadoPostIni = requestPost.execute(MOBILE_APP_URL+"recorridos_realizados_iniciar").get();
                Log.i("Resultado", resultadoPostIni);
                if (!resultadoPostIni.equals("NoInternet")) {

                    JSONObject returnArray = new JSONObject(resultadoPostIni);
                    if (!returnArray.getBoolean("error")) {
                        if (!returnArray.getBoolean("alejado")) {
                            String id_rr = returnArray.getString("id_recorrido_realizado");
                            //if(resultadoPostIni.length() <= 10 && !resultadoPostIni.equals("No guardo") && !resultadoPostIni.equals("alejado")){
                            tvInfo.setText("Recorrido Iniciado");
                            mlocManager.removeUpdates(mlocListener);

                            String fecha = dateFormater.format(new Date());
                            mDbHelper.eliminarRecorrido(1);
                            mDbHelper.agregarRecorrido(id_rr, fecha);

                            Bundle bundleEmisor2 = new Bundle();
                            Intent intent2 = new Intent(RecorridoActivity.this, RastreoActivity.class);

                            Log.i("Resultado",id_rr);
                            bundleEmisor2.putString("id_recorrido_realizado", id_rr);
                            bundleEmisor2.putString("hash_session", hash_session);
                            bundleEmisor2.putString("update_time", update_time);
                            bundleEmisor2.putString("id_bus", id_bus);
                            bundleEmisor2.putString("id_conductor", id_conductor);

                            intent2.putExtras(bundleEmisor2);
                            startActivity(intent2);
                        } else {
                            Toast.makeText(getApplicationContext(), "Esta muy alejado de la parada inicial acerquese mas y presione el boton actualizar", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "Hubo un error en el servidor al guardar el recorrido en el metodo recorridos_realizados_iniciar", Toast.LENGTH_LONG).show();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if(view.getId() == R.id.btnCerrarSesion1){
            Logout logOut = new Logout();
            try {
                String resultadoLogout = logOut.execute(hash_session).get();
                if(resultadoLogout.equals("0")){
                    MySQLiteHelperConductor baseDatos = new MySQLiteHelperConductor(RecorridoActivity.this);
                    //Intent intent3 = new Intent("com.mibus.ejemplo.LoginLayout");
                    Intent intent3 = new Intent(RecorridoActivity.this, LoginActivity.class);
                    baseDatos.deleteInfo(1);

                    mlocManager.removeUpdates(mlocListener);
                    Toast.makeText(getApplicationContext(),"Ha cerrado sesion satisfactoriamente",Toast.LENGTH_SHORT).show();

                    //startActivity(intent3);
                    this.finish();
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),"Ha ocurrido un error al cerrar sesion intentelo de nuevo",Toast.LENGTH_SHORT).show();
            }
        }else if(view.getId() == R.id.btnActualiarSpinner){
            tvInfo.setText("Esperando Posicion");
            id_ruta = null;
            id_horario = null;
            btnActualizarSpinner.setEnabled(false);
            mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,mlocListener,Looper.myLooper());
            hacerRequest();
        }
    }

    private class MyLocationListenerIni implements LocationListener{
        public void onLocationChanged(Location loc){
            latitud = loc.getLatitude();
            longitud = loc.getLongitude();
            velocidad = loc.getSpeed();

            if(id_horario != null && id_ruta != null && primeraVez){
                btnHacerRequest.setEnabled(true);
                primeraVez=false;
            }

            btnActualizarSpinner.setEnabled(true);
            tvInfo.setText("Posicion Encontrada");
            final MediaPlayer mp = MediaPlayer.create(RecorridoActivity.this,R.raw.posicion_encontrada);

            try {
                mp.start();
            }catch (Exception e){}
        }

        public void onProviderDisabled(String provider){
            Toast.makeText( getApplicationContext(),
                    "GPS Desactivado activelo por favor",
                    Toast.LENGTH_SHORT ).show();
        }

        public void onProviderEnabled(String provider){
            Toast.makeText( getApplicationContext(),
                    "GPS Activado",
                    Toast.LENGTH_SHORT).show();
        }

        public void onStatusChanged(String provider, int status, Bundle extras){}
    }

    private void hacerRequest(){
        try{
            RequestGet requestGet = new RequestGet(this);
            String resultado = requestGet.execute(MOBILE_APP_URL+"recorridos_get?hash_session="+hash_session).get();
            if (!resultado.equals("NoInternet")) {
                cJSON = new JSONArray(resultado);
                //cJSON = requestGet.execute(MOBILE_APP_URL+"recorridos_get?hash_session="+hash_session).get();     //cJSON contenedorJSON
                List<String> contenidoSpinner = new ArrayList<String>();

                btnHacerRequest.setEnabled(false);

                if (cJSON.length() > 0) {
                    contenidoSpinner.add("Seleccionar Ruta");

                    for (int i = 0; i < cJSON.length(); i++) {
                        JSONObject JSONrecorrido = cJSON.getJSONObject(i);
                        JSONObject JSONruta = JSONrecorrido.getJSONObject("Ruta");
                        if (!contenidoSpinner.contains(JSONruta.getString("nombre_ruta"))) {
                            contenidoSpinner.add(JSONruta.getString("nombre_ruta"));
                        }
                    }
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                            R.layout.spinner_item, contenidoSpinner);
                    spRutas.setAdapter(adapter);
                    spRutas.setOnItemSelectedListener(this);
                } else {
                    List<String> contenidoSpinnerHorario = new ArrayList<String>();
                    contenidoSpinner.add("No hay rutas disponibles");
                    contenidoSpinnerHorario.add("No hay horarios disponibles");
                    ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
                            android.R.layout.simple_spinner_item, contenidoSpinnerHorario);
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                            android.R.layout.simple_spinner_item, contenidoSpinner);

                    spRutas.setAdapter(adapter);
                    spHorarios.setAdapter(adapter2);
                }
            }else{
                Toast.makeText(getApplicationContext(),"No hay conexion a internet, por favor presione el boton actualizar", Toast.LENGTH_LONG).show();
            }
        }catch (Exception e){
            Toast.makeText(getApplicationContext(),"No se pudo obtener los recorridos, por favor presione el boton actualizar",Toast.LENGTH_LONG).show();
        }
    }

    public void onBackPressed() {
        Toast.makeText(getApplicationContext(),"No puede salir tiene que cerrar sesion",Toast.LENGTH_SHORT).show();
    }

    public void autoLoginRecorridoRealizado(){
        if (!mDbHelper.obtenerRecorrido(1).getAsString("_id").equals("no hay nada")){
            ContentValues informacionRecorrido = mDbHelper.obtenerRecorrido(1);
            String fechaActualStr = dateFormater.format(new Date());
            String fechaRecorridoStr = informacionRecorrido.getAsString("fecha_creacion");

            try {
                Date fechaActual = dateFormater.parse(fechaActualStr);
                Date fechaRecorrido = dateFormater.parse(fechaRecorridoStr);

                if (((fechaActual.getTime()-fechaRecorrido.getTime()) / (1000*60)) < 60){
                    Toast.makeText(getBaseContext(), "AutoRecorrido", Toast.LENGTH_SHORT).show();
                    tvInfo.setText("Recorrido Iniciado");
                    mlocManager.removeUpdates(mlocListener);

                    Bundle bundleEmisor2 = new Bundle();
                    Intent intent2 = new Intent(RecorridoActivity.this, RastreoActivity.class);

                    bundleEmisor2.putString("id_recorrido_realizado",informacionRecorrido.getAsString("id_recorrido_realizado"));
                    bundleEmisor2.putString("hash_session",hash_session);
                    bundleEmisor2.putString("update_time",update_time);
                    bundleEmisor2.putString("id_bus",id_bus);
                    bundleEmisor2.putString("id_conductor",id_conductor);

                    intent2.putExtras(bundleEmisor2);
                    startActivity(intent2);
                }else{
                    mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mlocListener, Looper.myLooper());
                }
            } catch (ParseException e) {
                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
                mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mlocListener, Looper.myLooper());
            }
        }else{
            mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mlocListener, Looper.myLooper());
        }
    }
}
